import {
    WsResponse,
    SubscribeMessage,
    WebSocketGateway,
    WebSocketServer,
    OnGatewayConnection,
    OnGatewayDisconnect,
    OnGatewayInit,
    ConnectedSocket,
    MessageBody
} from '@nestjs/websockets';
import path from 'path';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Server } from 'ws';
import { LongConnsService } from './long.conns.service';
import { AuthGuard } from '@utils/SHA256_token_auth.guard';
import { RedisService } from './redis.service';

//连接地址:dd

@WebSocketGateway({ path:'ws',cors: { origin: '*' } })
export class WechatGatewayService implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
    @WebSocketServer()
    server: Server;

    constructor(
        private longConnsService:LongConnsService,
        private authService: AuthGuard,
        private redisService:RedisService
    ) {
        console.log(this.server)
    }

    afterInit(server: Server) {
        console.log('what')

        this.server.on('connect', () => {
            console.log('what')
        })
    }
 
    handleConnection(client: WebSocket) {
        console.log('New client connected')
        this.longConnsService.addClient(client)
    }

    handleDisconnect(client: any) {
        console.log('Client disconnected')
        this.longConnsService.removeClient(client)
    }

    @SubscribeMessage('login')
    async onEvent(@ConnectedSocket() client: WebSocket, @MessageBody() data: any) {
        let redis = this.redisService.redis()

        // await redis.set("key","value")
        // const value = await redis.get('key')

        await this.longConnsService.login(client,data.userId,data.userInfo)
        return  null
    }
}